package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.SkuHasStockTo;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WareFeignService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.to.SpuInfoTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


/**
 * @author Administrator
 */
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    private ThreadLocal<OrderSubmitVo> submitVoThreadLocal = new ThreadLocal<>();
    @Autowired
    private CartFeignService cartFeignService;
    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        // 根据拦截器获取用户
        MemberRespVo memberRespVo = LoginUserInterceptor.threadLocal.get();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 采用多线程异步编排的方式
        CompletableFuture<Void> addressTask = CompletableFuture.runAsync(() -> {
            // 每个新建的线程都去添加之前请求的数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 远程查询所有的收货地址列表
            List<MemberAddressVo> memberAddress = memberFeignService.getMemberAddress(memberRespVo.getId());
            orderConfirmVo.setMemberAddressVos(memberAddress);
        }, threadPoolExecutor);
        CompletableFuture<Void> cartTask = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 远程查询购物车所有选中的购物项
            List<OrderItemVo> userCartItems = cartFeignService.getUserCartItems();
            // feign 在远程调用之前  feign在创建RequestTemplate之前会调用很多RequestInterceptor，可以利用RequestInterceptor将老请求头给加上
            orderConfirmVo.setItems(userCartItems);
        }, threadPoolExecutor).thenRunAsync(() -> {
            // 远程调用获得仓库数据
            List<OrderItemVo> items = orderConfirmVo.getItems();
            // 得到skuIds
            List<Long> skuIds = items.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
            R skusHasStock = wareFeignService.getSkusHasStock(skuIds);
            if (skusHasStock != null) {
                List<SkuHasStockTo> skusHasStockData = skusHasStock.getData(new TypeReference<List<SkuHasStockTo>>() {
                });
                Map<Long, Boolean> hasStockMap = skusHasStockData.stream().collect(Collectors.toMap(SkuHasStockTo::getSkuId, SkuHasStockTo::getHasStock));
                orderConfirmVo.setStocks(hasStockMap);
            }
        }, threadPoolExecutor);
        // 查询用户积分
        orderConfirmVo.setIntegration(memberRespVo.getIntegration());
        // 其他数据自动计算
        // 防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        // 服务器和页面各设置一个
        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(), token);
        orderConfirmVo.setOrderToken(token);
        // 等待两个远程任务执行完成   异步任务执行远程调用时会丢失请求上下文，oldRequest会为null
        CompletableFuture.allOf(addressTask, cartTask).get();
        return orderConfirmVo;
    }

    /**
     * 默认只要是运行时异常都会回滚
     *
     * @param vo
     * @return
     */
//    @GlobalTransactional
    @Transactional(rollbackFor = NoStockException.class)
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        // 共享VO
        submitVoThreadLocal.set(vo);
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        // 获取当前用户的登录信息
        MemberRespVo memberRespVo = LoginUserInterceptor.threadLocal.get();
        responseVo.setCode(0);
        // 下单 ：去创建订单 验证令牌 验价格 锁库存
        String orderToken = vo.getOrderToken();
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        // 验证令牌[令牌的对比和删除必须保证原子性] 0代表校验失败 1代表成功 使用lua脚本保证原子性
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<>(script, Long.class),
                Collections.singletonList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()),
                orderToken);
        if (result == 0L) {
            // 令牌校验不通过
            responseVo.setCode(1);
            return responseVo;
        } else {
            // 校验通过 下单 ：去创建订单 验证令牌 验价格 锁库存
            // 创建订单
            OrderCreateTo order = createOrder();
            // 验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                // 金额对比成功
                // 保存订单
                saveOrder(order);
                // 库存锁定 只要有异常回滚订单数据
                // 订单号、所有订单项信息(skuId skuNum skuName)
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                // 设置订单号
                wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());
                // 获取出要锁定的商品数据信息
                List<OrderItemVo> orderItemVos = order.getOrderItems().stream().map(orderItemEntity -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(orderItemEntity.getSkuId());
                    orderItemVo.setCount(orderItemEntity.getSkuQuantity());
                    orderItemVo.setTitle(orderItemEntity.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(orderItemVos);
                // 远程调用锁库存服务  库存成功了 但是因为网络问题 订单回滚库存不回滚
                // 为了保证高并发 库存服务自己回滚 可以发送消息给库存服务
                // 库存服务可以使用自动解锁模式
                R r = wareFeignService.orderLockStock(wareSkuLockVo);
                if (r.getCode() == 0) {
                    // 锁定成功 赋值完整的订单信息
                    responseVo.setOrder(order.getOrder());
//                     int i=10/0; // 订单回滚 库存不回滚
                    // 订单创建成功 给MQ发送消息
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
                    return responseVo;
                } else {
                    // 锁定失败
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }
            } else {
                // 金额对比失败
                responseVo.setCode(2);
                return responseVo;
            }
        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity order = baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order;
    }

    @Override
    public void closeOrder(OrderEntity entity) {
        // 查询当前订单的最新状态
        OrderEntity order = baseMapper.selectById(entity.getId());
        if (OrderStatusEnum.CREATE_NEW.getCode().equals(order.getStatus())) {
            // 关闭订单
            OrderEntity updateOrder=new OrderEntity();
            updateOrder.setId(entity.getId());
            updateOrder.setStatus(OrderStatusEnum.CANCLED.getCode());
            baseMapper.updateById(updateOrder);
            OrderTo orderTo=new OrderTo();
            BeanUtils.copyProperties(order,orderTo);
            // 关闭成功后 给mq发送一个消息
            rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
        }
    }

    /**
     * 保存订单相关数据
     *
     * @param orderCreateTo
     */
    private void saveOrder(OrderCreateTo orderCreateTo) {
        // 保存订单信息
        OrderEntity order = orderCreateTo.getOrder();
        order.setModifyTime(new Date());
        order.setCreateTime(new Date());
        baseMapper.insert(order);
        // 获取订单项信息
        List<OrderItemEntity> orderItems = orderCreateTo.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    private OrderCreateTo createOrder() {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        // 1、生成订单号
        String orderSn = IdWorker.getTimeId();
        OrderEntity order = builderOrder(orderSn);
        // 2、获取所有的订单项
        List<OrderItemEntity> orderItemEntities = builderOrderItems(orderSn);
        //  3、 验价
        computePrice(order, orderItemEntities);
        // 保存订单心心 和订单项信息
        orderCreateTo.setOrder(order);
        orderCreateTo.setOrderItems(orderItemEntities);
        return orderCreateTo;
    }

    /**
     * 计算价格相关
     *
     * @param order
     * @param orderItemEntities
     */
    private void computePrice(OrderEntity order, List<OrderItemEntity> orderItemEntities) {
        // 总价
        BigDecimal total = new BigDecimal("0.0");
        // 优惠价
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal intergration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        // 积分 、成长值
        Integer intergrationTotal = 0;
        Integer growthTotal = 0;
        // 订单总额 叠加每一个订单项的总额信息
        for (OrderItemEntity orderItemEntity : orderItemEntities) {
            // 总价
            total = total.add(orderItemEntity.getRealAmount());
            // 优惠价
            coupon = coupon.add(orderItemEntity.getCouponAmount());
            intergration = intergration.add(orderItemEntity.getIntegrationAmount());
            promotion = promotion.add(orderItemEntity.getPromotionAmount());
            // 积分信息和成长值
            intergrationTotal += orderItemEntity.getGiftIntegration();
            growthTotal += orderItemEntity.getGiftGrowth();
        }
        // 订单价格相关
        order.setTotalAmount(total);
        // 设置应付金额 （总额+运费）
        order.setPayAmount(total.add(order.getFreightAmount()));
        order.setCouponAmount(coupon);
        order.setPromotionAmount(promotion);
        order.setIntegrationAmount(intergration);
        // 设置积分和成长值
        order.setIntegration(intergrationTotal);
        order.setGrowth(growthTotal);
        // 设置删除状态(0-未删除 1-已删除)
        order.setDeleteStatus(0);
    }

    private OrderEntity builderOrder(String orderSn) {
        // 获取当前用户的登录信息
        MemberRespVo memberRespVo = LoginUserInterceptor.threadLocal.get();
        // 创建订单信息
        OrderEntity order = new OrderEntity();
        order.setMemberId(memberRespVo.getId());
        order.setOrderSn(orderSn);
        order.setMemberUsername(memberRespVo.getUsername());
        OrderSubmitVo orderSubmitVo = submitVoThreadLocal.get();
        // 远程获取收货地址和运费信息
        R fare = wareFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareData = fare.getData(new TypeReference<FareVo>() {
        });
        // 获取运费
        order.setFreightAmount(fareData.getFare());
        // 获取地址信息
        order.setReceiverCity(fareData.getAddress().getCity());
        order.setReceiverDetailAddress(fareData.getAddress().getDetailAddress());
        order.setReceiverName(fareData.getAddress().getName());
        order.setReceiverPhone(fareData.getAddress().getPhone());
        order.setReceiverPostCode(fareData.getAddress().getPostCode());
        order.setReceiverProvince(fareData.getAddress().getProvince());
        order.setReceiverRegion(fareData.getAddress().getRegion());
        return order;
    }

    /**
     * 构建所有订单项
     *
     * @return
     */
    private List<OrderItemEntity> builderOrderItems(String orderSn) {
        List<OrderItemVo> userCartItems = cartFeignService.getUserCartItems();
        if (!CollectionUtils.isEmpty(userCartItems)) {
            List<OrderItemEntity> itemEntities = userCartItems.stream().map(cartItem -> {
                // 构建订单项
                OrderItemEntity orderItem = builderOrderItem(cartItem);
                orderItem.setOrderSn(orderSn);
                return orderItem;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    /**
     * 构建单个订单项数据
     *
     * @param cartItem
     * @return
     */
    private OrderItemEntity builderOrderItem(OrderItemVo cartItem) {
        OrderItemEntity orderItem = new OrderItemEntity();
        // 1、订单信息 订单号
        // 2、商品的spu信息
        R spuInfoR = productFeignService.getSpuInfoBySkuId(cartItem.getSkuId());
        SpuInfoTo spuInfoRData = spuInfoR.getData(new TypeReference<SpuInfoTo>() {
        });
        orderItem.setSpuId(spuInfoRData.getId());
        orderItem.setSpuBrand(spuInfoRData.getBrandName());
        orderItem.setSpuName(spuInfoRData.getSpuName());
        orderItem.setCategoryId(spuInfoRData.getCatalogId());
        // 3、商品的sku信息
        orderItem.setSkuId(cartItem.getSkuId());
        orderItem.setSkuName(cartItem.getTitle());
        orderItem.setSkuPic(cartItem.getImage());
        orderItem.setSkuPrice(cartItem.getPrice());
        orderItem.setSkuAttrsVals(StringUtils.collectionToDelimitedString(cartItem.getSkuAttrValues(), ";"));
        orderItem.setSkuQuantity(cartItem.getCount());
        // 4、优惠信息 不做
        // 5、积分信息
        Integer intValue = cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue();
        orderItem.setGiftGrowth(intValue);
        orderItem.setGiftIntegration(intValue);
        // 6、订单项的价格信息
        orderItem.setPromotionAmount(BigDecimal.ZERO);
        orderItem.setCouponAmount(BigDecimal.ZERO);
        orderItem.setIntegrationAmount(BigDecimal.ZERO);
        // 当前订单项的实际金额 总额-各种优惠价格
        BigDecimal origin = orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuQuantity().toString()));
        // 原价减去优惠价得到最终价格
        BigDecimal realAmount = origin.subtract(orderItem.getCouponAmount())
                .subtract(orderItem.getPromotionAmount())
                .subtract(orderItem.getIntegrationAmount());
        orderItem.setRealAmount(realAmount);
        return orderItem;
    }
}